/**
 * @author denis.onishchenko@gmail.com
 */

package com.prapp.mediag;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;
import android.webkit.WebSettings;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

public final class PRApplication extends Application {

    static final String TAB_INDEX = "tabIndex";
    static final String POST_ID = "postId";

    private static final String SETTINGS_NAME = "PRApplication";

    private static final String SYNC_ITEMS_ON_START = "sync_items_on_start";
    private static final String SHOW_UNREAD_POSTS = "show_unread_posts";
    private static final String DOWNLOAD_IMAGES = "download_images";
    private static final String POST_TEXT_SIZE = "post_text_size";
    private static final String SHOW_POST_IMAGES = "show_post_images";
    private static final String CATEGORY_ID = "category_id";

    private static final String CONFIG_NAME = "config.xml";

    private Config config;
    private Map<Integer, Repository> repositories;
    private GoogleAnalyticsTracker gaTracker;

    public void onTerminate() {
        if (repositories != null)
            for (Repository repository : repositories.values())
                try {
                    repository.close();
                }
                catch (Throwable x) {
                    Log.e(getClass().getName() + ".onTerminate", "Can't close repository", x);
                }
        repositories = null;

        if (gaTracker != null)
            try {
                gaTracker.stop();
            }
            catch (Throwable x) {
                Log.e(getClass().getName() + ".onTerminate", "Can't stop GoogleAnalyticsTracker", x);
            }
        gaTracker = null;

        super.onTerminate();
    }

    int getTabCount() {
        List<Config.Tab> tabList = config.getTabList();
        return tabList.size();
    }

    Config.Tab getTab(int tabIndex) {
        return config.getTabList().get(tabIndex);
    }

    Class<?> getActivityClass(int tabIndex) {
        List<Config.Tab> tabList = config.getTabList();
        Config.Tab tab = tabList.get(tabIndex);

        if (tab instanceof Config.ContactsTab)
            return ContactsActivity.class;

        if (tab instanceof Config.EmailTab)
            return EmailActivity.class;

        if (tab instanceof Config.FeedsTab)
            return FeedsActivity.class;

        if (tab instanceof Config.HtmlTab)
            return HtmlActivity.class;

        return null;
    }

    void initialize() {
        try {
            InputStream is = getAssets().open(CONFIG_NAME, AssetManager.ACCESS_STREAMING);
            try {
                config = Config.parse(is);
            }
            finally {
                is.close();
            }
        }
        catch (Throwable x) {
            throw new RuntimeException(x);
        }


        if (config == null) throw new RuntimeException("Can't read config");

        List<Config.Tab> tabList = config.getTabList();

        if (tabList != null) {
            repositories = new HashMap<Integer, Repository>();

            for (int tabIndex = 0; tabIndex < tabList.size(); tabIndex++) {
                Config.Tab tab = tabList.get(tabIndex);

                if (tab instanceof Config.FeedsTab) {
                    Resources resources = getResources();

                    String allCategoryName = resources.getString(R.string.All);
                    String unreadCategoryName = resources.getString(R.string.Unread);
                    String favoriteCategoryName = resources.getString(R.string.Favorite);

                    List<Category> sCategories = new ArrayList<Category>();

                    sCategories.add(new Category(Category.ALL_CATEGORY_ID, allCategoryName));
                    sCategories.add(new Category(Category.UNREAD_CATEGORY_ID, unreadCategoryName));
                    sCategories.add(new Category(Category.FAVORITE_CATEGORY_ID, favoriteCategoryName));

                    Config.FeedsTab feedsTab = (Config.FeedsTab) tab;

                    String dbName = feedsTab.getDatabase();
                    List<Config.Feed> feedList = feedsTab.getFeedList();

                    List<Category> categories = new ArrayList<Category>();

                    if (feedList != null) {
                        for (Config.Feed feed : feedList) {
                            String categoryName = feed.getName();
                            String categoryUrl = feed.getUrl();

                            if (categoryName == null || categoryUrl == null) continue;

                            categories.add(new Category(categoryName, categoryUrl));
                        }
                    }

                    Repository repository = new Repository(this, getPackageName(), dbName, sCategories, categories);
                    repositories.put(tabIndex, repository);
                }
            }
        }

        String ga = config.getGa();
        if (ga != null)
            try {
                gaTracker = GoogleAnalyticsTracker.getInstance();
                gaTracker.start(ga, this);
            }
            catch (Throwable x) {
                Log.w(getClass().getName() + ".initialize", "Can't start GoogleAnalyticsTracker", x);
                gaTracker = null;
            }
    }

    Repository getRepository(int tabIndex) {
        return repositories.get(tabIndex);
    }

    boolean getSyncItemsOnStart() {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        return preferences.getBoolean(SYNC_ITEMS_ON_START, true);
    }

    void setSyncItemsOnStart(boolean value) {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(SYNC_ITEMS_ON_START, value);
        editor.commit();
    }

    int getDownloadImages() {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        return preferences.getInt(DOWNLOAD_IMAGES, 1);
    }

    void setDownloadImages(int value) {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(DOWNLOAD_IMAGES, value);
        editor.commit();
    }

    boolean getShowUnreadPosts() {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        return preferences.getBoolean(SHOW_UNREAD_POSTS, false);
    }

    void setShowUnreadPosts(boolean value) {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(SHOW_UNREAD_POSTS, value);
        editor.commit();
    }

    WebSettings.TextSize getPostTextSize() {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        String name = preferences.getString(POST_TEXT_SIZE, WebSettings.TextSize.NORMAL.name());
        return WebSettings.TextSize.valueOf(name);
    }

    void setPostTextSize(WebSettings.TextSize value) {
        String name = value.name();
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(POST_TEXT_SIZE, name);
        editor.commit();
    }

    boolean getShowPostImages() {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        return preferences.getBoolean(SHOW_POST_IMAGES, true);
    }

    void setShowPostImages(boolean value) {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(SHOW_POST_IMAGES, value);
        editor.commit();
    }

    long getCategoryId() {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        return preferences.getLong(CATEGORY_ID, Category.ALL_CATEGORY_ID);
    }

    void setCategoryId(long value) {
        SharedPreferences preferences = getSharedPreferences(SETTINGS_NAME, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong(CATEGORY_ID, value);
        editor.commit();
    }

    void trackPageView(String value) {
        if (gaTracker == null) return;

        gaTracker.trackPageView(value);
        gaTracker.dispatch();
    }
}
